package org.suburban.servlet.schedule;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * Base class for all schedule crackers (HTML 'scedeule' parser)
 * 
 * Known subclasses:
 * 	   	{@link}UpToTimeScheduleCracker{@link}
 * 		{@link}FullDayScheduleCracker{@link}
 *  
 *  @author Alexey Palamarchuk (slonnik@gmail.com)
 *
 */
class ScheduleCracker extends DefaultHandler {
	/** parser outout*/
	final StringBuilder out;
	/** flag to indicate, that we started parsing schedule table*/
	boolean parsingTable = false;
	/** flag to indicate, tha we started parsing departure time*/
	boolean parsingTime = false;
	/**flag to indicate that we start parsing end time*/
	boolean parsingArrivalTime = false;
	/** flag to indicate, tha we started parsing departure period*/
	boolean parsingPeriod = false;
	/** flag to indicate that output should be XML formatted*/
	final boolean isXml;
	/** schedule header*/
	final String header;
	/** reference to local item*/
	final ScheduleItem item = new ScheduleItem();
	
	/**
	 * Class to store schedule
	 */
	static class ScheduleItem
	{
		/** departure time*/
		String departure;
		/** arrival time*/
		String arrival;
		/** schedule description*/
		String description;
		/** schedule period*/
		String period;
		
		/**clear internal state */
		void clear()
		{
			departure = null;
			arrival = null;
			description = null;
			period = null;
			
		}
		@Override
		public String toString() {
			
			return String.format("%1$s > %2$s | %3$s ", departure, arrival, period);
		}
	}
	
	/**
	 * ctor
	 * @param out - stream to print parsing result
	 * @param header - schedule header
	 * @param isXml	 - true, if output should be XML formatted, otherwise false
	 */
	ScheduleCracker(StringBuilder out, String header, boolean isXml)
	{
		this.out = out;
		this.header = header;
		this.isXml = isXml;
	}
	@Override
	public void startDocument() throws SAXException {
		
		/** add header to output*/
		if(isXml)
		{
			out.append("<body>");
        	out.append("<p>").append(header).append("</p>");
        	out.append("<table>");
		}
		else
		{
			out.append(header).append("\n");
		}
	}
	
	@Override
	public void endDocument() throws SAXException {
		/** add footer*/
		if(isXml)
		{
			out.append("</table>").append("</body>");
		}
	}
}
